<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/6
 * Time: 11:26
 */

namespace App\Http\Controllers\Home;


use App\Http\Controllers\Controller;
use App\Model\Address;
use App\Model\Apply;
use App\Model\Members;
use App\Model\Prize;
use App\Model\PurchaseOrder;
use App\Model\RecordBonus;
use App\Model\RecordTransaction;
use App\Model\Replenish;
use App\Model\ShopGoods;
use App\Model\ShopGoodsClassify;
use App\Model\ShopGoodsImg;
use App\Model\ShopMemberCart;
use App\Model\ShopOrder;
use App\Model\ShopOrderComment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Session;
use App\Model\MembersLevel;

class ShopController extends Controller
{
    /*
     * 显示购页面
     */
    public function index(){

        return view('Home.timeted.index');
    }
    /**
     * 限时购商品表
     * @param Request $request
     * @return array
     * @throws \Exception
     */
    public function goods(Request $request)
    {
        $data = $request->all();
        if (empty($data)) {
            return ['code' => 0, 'data' => '参数错误'];
        }
        switch ($data['class']) {
            case 'select': //查询
                //Redis::del("shopData");
                //$shopData = Redis::get("shopData");
                //$shopData = unserialize( $shopData );
                //$classifyDate = Redis::get("classifyDate");
                //$classifyDate = unserialize( $classifyDate );
                //$classifysFirst = Redis::get("classifyFirst");
                //$classifysFirst = unserialize($classifysFirst);
                //if ( empty($shopData) || empty($classifysFirst) || empty($classifyDate)){
                    $table = ShopGoodsClassify::where(['type' => 4])->select('id');
                    $classify = $table->get()->toArray();
                    $pid = [];
                    if (!empty($classify)) {
                        foreach ($classify as $value) {
                            $pid[] = $value['id'];
                        }
                    } else {
                        return ['code' => 0, 'data' => '暂时还没有商品'];
                    }
                    //查询出所有分类
                    $classifyDate = ShopGoodsClassify::where(['type' => 4, 'pid' => 11])->select('id', 'name')->get()->toArray();
                    $classifyFirst = ShopGoodsClassify::where(['type' => 4, 'pid' => 11])->limit(1)->value('id');
                    $classifysFirst = $data["two_tid"] != 0 ? $data["two_tid"] : $classifyFirst;
                    //查询商品
                    $shopData = array();
                    foreach ( $classifyDate as $key => $v ){
                        $shop = ShopGoods::select(
                            'cid',
                            'id',
                            'goodsname',
                            'spec',
                            'originalprice',
                            'startTime',
                            'timeprice',
                            'two_tid')
                            ->where(['type' => 1, 'status' => 1, 'cid' => 11 ,'two_tid' => $v['id'] ])
                            ->paginate(4);
                        foreach ($shop as $k => $value) {
                            $img = ShopGoodsImg::where(['gid' => $value['id']])->select('img')->first();
                            $shop[$k]['img'] = empty($img->img) ? '' : $img->img;
                            if ( time() < strtotime($shop[$k]['startTime'])){
                                $shop[$k]['is_open'] = -1;
                            } else {
                                $shop[$k]['is_open'] = 1;
                            }
                        }
                        $shopData[$v['id']] = $shop;
                    }

                    //Redis::setex( "shopData" , 86400 , serialize($shopData));
                    //Redis::setex( "classifyDate" , 86400 , serialize($classifyDate));
                    //Redis::setex( "classifyFirst" , 86400 , serialize($classifysFirst));
               // }

         if ( $shopData && $classifysFirst && $classifyDate ) {
                    return ['code' => 1, 'data' => $shopData, 'classifyDate' => $classifyDate, 'classifyFirst' => $classifysFirst];
                } else {
                    return ['code' => 0, 'data' => '没有数据'];
                }
                break;
            case 'find':   //查询一条数据
                $goods = ShopGoods::where('id',$data['id'])->first();
                $goodsImgName = ShopGoodsImg::where('gid',$data['id'])->select('img')->get()->toArray();
                $goods['img'] = $goodsImgName;
                $record = ShopOrder::join('members','members.uid','=','shop_order.uid')
                    ->select(
                        'members.user_name',
                        'shop_order.*'
                    )
                    ->orderBy('created_at','desc')
                    ->where(['status'=>1])
                    ->get()->toArray();
//                var_dump($record);exit;
                if ($goods || $record) {
                    return ['code'=>1,'data'=>$goods,'recordData'=>$record];
                } else {
                    return ['code'=>0,'data'=>'设置失败'];
                }
                break;
        }

    }

    /*
     * 商品详情
     */
    public function detil(){

        return view('Home.timeted.orderDetil');
    }


    /*
     * 生成订单
     */
    public function order(Request $request){
        $data = $request->all();
        if(empty($data)){
            return ['code' => 0, 'data' => '没有数据'];
        }
        $user = session('home_user');
        //商品表
        $ShopGoodsModel = new ShopGoods();
        $membersModel = new Members();
        //订单详情表
        $ShopOrderCommentModel = new ShopOrderComment();
        switch ($data['class']) {
            case 'add': //查询
                if (empty($data['goods'])) {
                    return ['code' => 0, 'data' => '没有商品'];
                }
                $goodsIds = [];
                foreach ($data['goods'] as $k => $v) {
                    if(intval($v['number']) < 0 || intval($v['number']) == ''){
                        return ['code' => 0, 'data' => '数量错误'];
                        break;
                    }
                    $goodsIds[] = $v['goodsid'];
                }
                DB::beginTransaction(); //开启事务
                $goods = $ShopGoodsModel->get_goods('',$goodsIds);

                $totalPrice = 0;   //总价格
                $number = 0;
                $freight = 10;//运费
                $weight = 0;//重量
                foreach ($goods as $k => $v){
                    foreach ($data['goods'] as $key => $val) {
                        if($val['goodsid'] == $v['id']) {

                            if ($data['price'] >= $v['originalprice']) {  //限时价格 等于 商品原价
                                $startTime = strtotime($v['startTime']);
                                $timeprice = count(json_decode($v['timeprice']));//限时天数
                                if (($startTime + ($timeprice * 3600 * 24)) > time()) {
                                    //限时购未结束
                                    $totalPrice += (intval(json_decode($v['timeprice'])[intval((time() - $startTime) / (60 * 60 * 24))] * $val['number']));
                                }else{
                                    //限时购结束  原价X数量
                                    $totalPrice += (intval($val['number']) * $v['originalprice']);
                                }
                            } else {
                                $totalPrice += (intval($val['number']) * $data['price']);
                            }



                            $number +=$val['number'];
                            $weight += ($val['number'] * $v['weight']);
                            $data['goods'][$key]['sold'] = $val['number'] + $v['sold'];
                            //$totalPrice += (intval($val['number']) * $data['price']);
                            $data['goods'][$key]['price'] = $v['rulingprice'];
                            $data['goods'][$key]['totalcnf'] = $v['totalcnf']; //0 拍下减库存 1 付款减库存 2 永久不减
                            $data['goods'][$key]['total'] = $v['total'];
                            $data['goods'][$key]['goodsname'] = $v['goodsname']; //商品名字
                        }
                    }
                }
                $weight = ceil($weight);
                $freight = ($weight>1)?($weight-1)*5+$freight:$freight;
                $totalPrice = intval($totalPrice * 100)/100 + $freight ; //保留两位小数
                //创建订单
                $order = [
                    'uid'           => $user->uid,
                    'openid'        => $user->openid,
                    'num'        => $val['number'],
                    'ordertype'     => 4, //1 直商城 2 微商城 3 0元商城 0 限时购
                    'ordersn'       => ORDER_SN(),
                    'price'         => $totalPrice,
                    'originalprice' => $v['originalprice'],
                    'freight'       => $freight, //运费
                    'status'        => 0,//-1取消状态，0代付款，1为已付款，2为已发货，3为成功
                    'createtime'    => time()
                ];
//               var_dump($order);exit;
                $orders=ShopOrder::create($order);
                 $orderID =$orders['id'];
//                var_dump($orderID);exit;
                if ($orderID) {

                    $cart = array(); //购物车id
                    $orderComment = array();
                    foreach ($data['goods'] as $key => $val) {
                        if($val['totalcnf'] == 0){ //0 拍下减库存 1 付款减库存 2 永久不减
                            $sold = $ShopGoodsModel->where(['id'=>$val['goodsid']])->update(['total' => ($val['total'] - $val['number']),'sold' => $val['sold']]);
                            if($sold == false){
                                DB::rollback();  //回滚
                                break;
                                return ['code'=>0,'data'=>'数据错误'];
                                exit();
                            }
                        }
                        $cart[] = $val['id']; //获取购物车id
                        $orderComment[] = [
                            'uid'           => $user->uid,
                            'orderid'       => $orderID,
                            'openid'        => $user->openid,
                            'goodsid'       => $val['goodsid'],
                            'price'         => $data['price'],
                            'goodsname'     => $val['goodsname'],
                            'number'        => $val['number'],
//                            'specs'         => $val['specs'],
                            'createtime'    => time(),
                        ];
                    }

                    if(!empty($orderComment)){
                        $rico = $ShopOrderCommentModel->insert($orderComment);
                        if ($rico){
                            //直接购买
                            if(isset($data['type'])){
                                DB::commit();  //提交
                                return ['code'=>1,'data'=>['id'=>$orderID,'data'=>'添加成功']];
                            }

                        } else {
                            DB::rollback();  //回滚
                            return ['code'=>0,'data'=>'添加失败'];
                        }
                    }
                } else {
                    DB::rollback();  //回滚
                    return ['code' => 0, 'data' => '设置失败'];
                }
                break;
            case 'pickSelf'://点自提时,运费的重新计算
                $member = $membersModel->find_members( ['uid' => $user->uid ], ['voucher', 'credit1', 'credit2', 'credit4' ] );
                if ( $data['pick'] == 1 ) {//自提
                    $payMoney = $data['totalPay'];
                } else {
                    $payMoney = $data['totalPay'] + $data['freight'];
                }  
            $ricos = FIGUR( $member->voucher, $member->credit1, $member->credit2, $member->credit4, $payMoney );
                if ( $ricos['code'] == 1 ) {
                    return ['code' => $ricos['code'] ,'data' =>'支付总额重新计算成功', 'rico' => $ricos ];
                } else {
                    return ['code' => $ricos['code'] ,'data' =>'余额不足', 'rico' => $ricos ];
                }  
                break;     
            case 'pay': //确定支付
                $member = $membersModel->find_members(['uid' => $user->uid],['voucher','credit1','credit2','credit3','credit4','credit5','level','stores_number']);
                //获取收货地址
                $address = Address::where(['id' => $data['addressId']])->first();

                //获取订单
                $order = ShopOrder::where(['id'=>$data['id']])->first();
                $goodsname = ShopOrderComment::where('orderid',$order['id'])->value('goodsname');
                if($order['status'] == 1){
                    return ['code' => 1 ,'data' =>'订单已支付，请勿重复支付！'];
                }
                //记录订单之前各会员的奖励币余额记录
                $this->credit2Record( $order['ordersn'], $user->uid);
                //是否自提
                $is_self = 0;
                $goodsMoney = $data['money']['voucher'] + $data['money']['credit1'] + $data['money']['credit2'] + $data['money']['credit4'];
                if( $data['pick'] == 1 ){ //判断用户是否是自提
                    $is_self = 1;
                    $moneys = $goodsMoney;
                } else {
                    $moneys = $goodsMoney - $data['freight'];
                }
                $memberAllMoneysTo = $member->voucher + $member->credit1 + $member->credit2 + $member->credit4;
                if ( $memberAllMoneysTo < $goodsMoney ) {
                    return ['code' => 0 ,'data' =>'余额不足'];
                }
                //启动事务
                DB::beginTransaction();
                try{
                    //扣款
                    $money = [
                        'voucher' => $member->voucher - $data['money']['voucher'],
                        'credit1' => $member->credit1 - $data['money']['credit1'],
                        'credit2' => $member->credit2 - $data['money']['credit2'],
                        'credit4' => $member->credit4 - $data['money']['credit4']
                    ];
                    Members::where(['uid' => $user->uid])->update($money);
                    //修改订单状态

                    ShopOrder::where(['id' =>$data['id']])->update( [
                        'status' => 1,
                        'is_self' => $is_self,
                        'price'   => $goodsMoney,
                        'paytime' => time(),
                        'addressid' => $data['addressId'],
                        'receipt_name'=> $address['name'],
                        'receipt_adr'=> $address['province'].$address['city'].$address['district'].$address['address'],
                        'receipt_phone'=> $address['phone'] ] );
                    //生成交易记录
                    $transaction = [
                        'uid' => $user->uid,
                        'ordersn' => $order['ordersn'],
                        'money' => - $goodsMoney,
                        'type' => 1,
                        'time' => time(),
                        'explain' => $goodsname.'购买',
                        'remark' => '代金劵 : '.-$data['money']['voucher'].',电子币 : '.-$data['money']['credit1'].' , 奖励币 : '.-$data['money']['credit2'].' , 积分 : '.-$data['money']['credit4']
                    ];
                    RecordTransaction::create($transaction);

                    //会员购买计算奖励提成
                    $prizeData = new Prize();
                    $prizeData->getPrize( $user['uid'], $moneys, $order['num'], $order['ordersn'] ,$goodsname);
                //计算区域代理提成
                if($address){
                    $prizeData->agency( $moneys, $address['province'], $address['city'], $address['district'], $user['uid'], $order['num'], $order['ordersn'] ,$goodsname );
                }
                //提交事物
                    DB::commit();
                }catch (\Exception $exception){
                    //回滚
                    DB::rollBack();
                    return ['code' => 0 ,'data' =>'支付失败'];
                }
                return ['code' => 1 ,'data' =>'支付成功'];
                break;
        }
    }

    /*
     * 提交订单页面
     */
        public function getOrder(){

            return view('Home.timeted.ordercomment');
        }
    /*
        * 提交订单页面
        */
    public function centerOrder(){

        return view('Home.timeted.detail');
    }

   /*
    * 个人购买面膜奖励记录页面
    */
    public  function total(){

        return view('Home.member.earning');
    }

    /*
     * 个人购买面膜奖励
     */
    public function getTotal(Request $request){
         $data  =  $request->all();
         if($data['uid']){
             $record = Members::where('uid',$data['uid'])
                 ->select(
                     'dnum','num','total'
                 )
                 ->first();
             if ( $record['num'] == '' ){
                 $record['num'] = 0;
             }
             if ( $record['total'] == ''){
                 $record['total'] = '0.00';
             }
             if ( $record['dnum'] == ''){
                 $record['dnum'] = 0;
             }
        if($record){
            return ['code' => 1 ,'data' =>$record ];
        }else{
            return ['code' => 0 ,'data' =>"没有数据"];
        }
        }

    }

    /**
     * 记录订单之前各会员的奖励币余额记录
     * @param int $uid 用户ID
     * @param string $ordersn     统一订单
     * @return array
     */
    public function credit2Record( $ordersn, $uid )
    {
        $ShopOrder = new ShopOrder();
        $UserModel = new Members();
        $orderMemberCredit2Datas = [];
        $orderMemberCredit2Uid = [];
        $orderMemberCredit2Uids = [];
        $memberLastCredit2Data = $ShopOrder->where( [ 'ordersn' => $ordersn ] )->value( 'last_credit2s' );
        if ( $memberLastCredit2Data != "" ) {
            $memberLastCredit2Data = unserialize( $memberLastCredit2Data );
        } else {
            $memberLastCredit2Data = [];
        }
        $memberLastCredit2 = [];
        $memberLastData = $UserModel->where([ 'uid' => $uid ])->select( 'uid', 'name', 'user_name', 'voucher','credit1', 'credit2', 'credit4' )->first();
//        var_dump($memberLastData);exit;
        $memberLastCredit2['uid'] = $memberLastData['uid'];
        $memberLastCredit2['name'] = $memberLastData['name'];
        $memberLastCredit2['user_name'] = $memberLastData['user_name'];
        $memberLastCredit2['voucher'] = $memberLastData['voucher'];
        $memberLastCredit2['credit1'] = $memberLastData['credit1'];
        $memberLastCredit2['credit2'] = $memberLastData['credit2'];
        $memberLastCredit2['credit4'] = $memberLastData['credit4'];
        if ( $memberLastCredit2Data ) {
            foreach ($memberLastCredit2Data as $key => $value) {
                array_push( $orderMemberCredit2Uid, $value['uid'] );
            }
            if ( !in_array( $uid, $orderMemberCredit2Uid ) ) {
                array_push( $memberLastCredit2Data, $memberLastCredit2 );
            }
            $Credit2SaveData = serialize( $memberLastCredit2Data );
        } else {
            if ( count( $orderMemberCredit2Datas ) > 0 ) {
                foreach ($orderMemberCredit2Datas as $key => $value) {
                    array_push( $orderMemberCredit2Uids, $value['uid'] );
                }
                if ( !in_array( $uid, $orderMemberCredit2Uids ) ) {
                    array_push( $orderMemberCredit2Datas, $memberLastCredit2 );
                }
            } else {
                array_push( $orderMemberCredit2Datas, $memberLastCredit2 );
            }
            $Credit2SaveData = serialize( $orderMemberCredit2Datas );
        }
        $ShopOrder->where( [ 'ordersn' => $ordersn ] )->update( [ 'last_credit2s' => $Credit2SaveData ] );
    }
}